import { useState, useEffect, useMemo, useContext } from "react";
import { NavBar, List, SearchBar, Image, InfiniteScroll, IndexBar } from "antd-mobile";
import { useHistory, useRouteMatch } from 'react-router-dom';
import pinyin from 'pinyin';

import AvatarImage from "../../../components/AvatarImage";
import { MySdkStoreContext } from '../../../context';

import "./style.scss";

export default function() {
  // 初始化key为字母的object
  const groupsKey = useMemo(() => {
    let groupsKey = {};
    const charCodeOfA = 'A'.charCodeAt(0);

    Array(27)
      .fill('')
      .map((_, i) => {
        groupsKey[i === 26 ? '#' : String.fromCharCode(charCodeOfA + i)] = [];
      });

    return groupsKey;
  });


  // 将object类型转换为Array类型数据，忽略空值
  const mapToArray = (map) => {
    return Object.keys(map)
      .filter(key => map[key]?.length)
      .map((title) => ({
        title,
        items: map[title]
      }));
  }

  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [group, setGroup] = useState(mapToArray(groupsKey));
  const { params: { cid } } = useRouteMatch();
  const [settings, setSettings] = useState({});
  const [membersPagination, setMembersPagination] = useState({ pageIndex: 1, totalItemCount: 0, next: 0 });
  const [admin, setAdmin] = useState([]);

  // 获取群成员
  const getMember = async (pageIndex) => {
    const { rows, current, next, totalItemCount } = await mySdkStore.sdk.listGroupMembers({ cid, pageIndex, pageSize: 20 });
    setMembersPagination({ pageIndex: current, totalItemCount, next: +next });
    rows.forEach((item) => {
      const name = item.userName || item.nickName;
      const letters = pinyin(name, { style: pinyin.STYLE_FIRST_LETTER });
      const code = (letters[0]?.[0]?.[0] || '').toUpperCase();
      if (groupsKey[code]) {
        groupsKey[code].push(item);
      } else {
        groupsKey['#'].push(item);
      }
    });
    setGroup(mapToArray(groupsKey));
  }

  // 获取群主、群管理员列表
  const getAdminUserInfo = async () => {
    const { adminUsers, ownerId } = await mySdkStore.sdk.querySingleConversation({ cid });
    const { rows } = await mySdkStore.sdk.batchQueryUserInfo({ userIds: [ownerId, ...adminUsers] });
    setAdmin(rows.map(item => item.userId === ownerId ? {...item, isOwner: true } : item));
  }

  // 获取群设置信息
  const querySetting = async () => {
    const { groupSetting } = await mySdkStore.sdk.queryGroupSetting({ cid });
    setSettings(groupSetting);
  }

  useEffect(async () => {
    await getAdminUserInfo();
    await getMember(1);
    await querySetting();
  }, []);

  return (<div className="groupMemberPage" style={{ height: window.innerHeight }}>
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>群成员</NavBar>
      {/* tood: 没有关键词搜索参数 */}
      {/* <SearchBar style={{ '--background': '#ffffff', margin: 12 }} placeholder="搜索" onSearch={() => handleSearch()} /> */}
      <List style={{ '--align-items': 'top' }}>
        {admin.map(item => {
          return <List.Item
              key={item.userId}
              prefix={<AvatarImage
              src={item.avatarUrl}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
              style={{ marginTop: 12, borderRadius: 8 }}
              fit='cover'
              width={42}
              height={42}
              preventLink={!settings.isAllowMemberTalkSecret}
            />}
            description={<>ID: {item.userId}</>}
            extra={<a className="role">{item.isOwner ? '群主': '管理员' }</a>}
          >{item.userName || item.nickName}</List.Item>
        })}
      </List>
      <IndexBar>
        {group.map(g => {
          const { title, items } = g;
          return (
            <IndexBar.Panel
              index={title}
              title={title}
              key={`${title}`}
            >
            <List>
              {items.map(item => {
                return <List.Item
                    key={item.userId}
                    prefix={<AvatarImage
                    nickName={item.nickName}
                    userName={item.userName}
                    userId={item.userId}
                    src={item.avatarUrl}
                    style={{ borderRadius: 8 }}
                    fit='cover'
                    width={42}
                    height={42}
                    preventLink={!settings.isAllowMemberTalkSecret}
                  />}
                  description={<>ID: {item.userId}</>}
                >{item.userName || item.nickName}</List.Item>
              })}
            </List>
          </IndexBar.Panel>
          )
        })}
      </IndexBar>
      <InfiniteScroll loadMore={() => getMember(membersPagination.pageIndex + 1)} hasMore={membersPagination.totalPage > membersPagination.pageIndex} />
  </div>
  )
}